package com.zfy.tingshu.search.config;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @author 86188
 * @version v1.0
 * @project tingshu-parent
 * @Date 2025/9/4 11:50
 * @company []
 * @description
 */
@Component
public class ThreadPoolExecutorConfig {

    //自定义线程池
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        //自定义线程池：因为使用工具类创建的线程池，要么是阻塞队列，要么是最大线程个数默认是Integer.max_avalue(21亿) 造成oom
        //获取当前cpu核数
        int cpuCoreNum = Runtime.getRuntime().availableProcessors();
        System.out.println("cpuCoreNum = " + cpuCoreNum);
        return new ThreadPoolExecutor(
                //核心线程数:业务需求：io 2n/cpu n+1
                cpuCoreNum * 2,
                //最大线程数
                cpuCoreNum * 2,
                //空闲线程存活事件
                3,
                //时间单位
                TimeUnit.SECONDS,
                //阻塞队列
                new ArrayBlockingQueue<>(100),
                //线程工厂
                Executors.defaultThreadFactory(),
                //拒绝策略
                new ThreadPoolExecutor.AbortPolicy()
        );
    }
}
